#include "desktop_previewer_widget.h"
#include "ui_desktop_previewer.h"
#include <qpushbutton.h>
#include <iostream>
#include <QMetaObject>
#include <QMutex>
#include <QQueue>
#include <qlabel.h>
#include <QString>
#include "helper.h"
#include "d3d_helper.h"
#include "logger.h"


DesktopPreviewerWidget::DesktopPreviewerWidget(QWidget* parent) :
    QWidget(parent),
    ui(new Ui::DesktopPreviewerWidget)
{
    ui->setupUi(this);
    this->init_ctrl();
}

DesktopPreviewerWidget::~DesktopPreviewerWidget()
{
    delete ui;
}

void DesktopPreviewerWidget::init_ctrl()
{
    monitors_ = DisplayMonitor::enumerate();
    for (auto& monitor : monitors_)
    {
        QString name = (monitor->get_is_primary() ? (u8"主屏幕") : (u8"扩展屏"));
        QString id = QString::number(monitor->get_id());

        ui->combScreenIndex->addItem( QString("%1 - %2") .arg(name) .arg(id));
    }

    connect(ui->btnOpen, &QPushButton::clicked, this, &DesktopPreviewerWidget::slot_btn_open);
    connect(ui->btnClose, &QPushButton::clicked, this, &DesktopPreviewerWidget::slot_btn_close);
}

void DesktopPreviewerWidget::paintEvent(QPaintEvent*)
{
}

void DesktopPreviewerWidget::slot_btn_open()
{
    /* dxgi采集器 */
    int width = 0, height = 0;
    Helper::System::get_display_resolution(0, width, height);

    capturer_ = std::make_shared<DXGICapturer>();
    DXGICapturerParams::shared params = std::make_shared<DXGICapturerParams>();
    params->set_width(width);
    params->set_height(height);
    params->set_fps(30);
    params->set_display_monitor(monitors_[ui->combScreenIndex->currentIndex()]);
    params->set_cb_frame_type(ENUM_MEDIA_FRAME_HARDWARE_TYPE);
    params->set_cb([&](void* arg, IAVFrame::shared frame) {
        auto v_frame = std::dynamic_pointer_cast<D3d11VideoFrame>(frame);

        if(d3d_renderer_)
            d3d_renderer_->render(v_frame);
    });
    capturer_->initialize(params);
    
    /* d3d渲染器 */
    d3d_renderer_ = std::make_shared<D3D11Renderer>();
    auto d3d_params = std::make_shared<D3D11RendererParams>();
    d3d_params->set_hwnd(HWND(ui->window->winId()));
    d3d_renderer_->initialize(d3d_params);

    capturer_->open();
}

void DesktopPreviewerWidget::slot_btn_close()
{
    if (capturer_)
    {
        capturer_->close();
        capturer_->uninitialize();
        capturer_.reset();
    }

    if (d3d_renderer_)
    {
        d3d_renderer_->uninitialize();
        d3d_renderer_.reset();
    }

    //recreate_window_widget();
}

void DesktopPreviewerWidget::recreate_window_widget()
{
    if (ui->window) {
        ui->window->deleteLater();
    }

    QLabel* label = new QLabel(this);
    label->setObjectName("window");
    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    label->setStyleSheet("background-color: black;");
    label->setAlignment(Qt::AlignCenter);

    ui->verticalLayout->addWidget(label);
    ui->window = label;
}
